package com.xunker.appointment.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.xunker.appointment.model.hospital.Hospital;
import com.xunker.appointment.repository.HospitalRepository;
import com.xunker.appointment.service.HospitalService;
import com.xunker.appointment.utils.BeanUtils;
import com.xunker.appointment.vo.hospital.CountVo;
import com.xunker.appointment.vo.hospital.HospitalVo;
import com.xunker.appointment.vo.hospital.ProAndCityVo;
import com.xunker.client.DictFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private DictFeignClient dictFeignClient;//通过服务中心调用service_dict_manager微服务模块中的方法
    @Override
    public void save(Map<String, Object> objectMap) {
        //参数转成Hospital对象
        final String jsonString = JSONObject.toJSONString(objectMap);
        final Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);
        //判断是否已存在相同数据
        Hospital hospital_1=hospitalRepository.getHospitalByHospitalCode(hospital.getHospitalCode());
        if(hospital_1==null){ //不存在，添加
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setDeleted(0);
            hospitalRepository.insert(hospital);
        }else {//存在修改
            hospital_1.setStatus(hospital.getStatus());
            hospital_1.setUpdateTime(hospital.getUpdateTime());
            hospital_1.setDeleted(0);
            hospitalRepository.save(hospital_1);
        }
    }

    @Override
    public Hospital getByHospitalCode(String hospitalCode) {
        return hospitalRepository.getHospitalByHospitalCode(hospitalCode);
    }

    @Override
    public Map<String, Object> getHospitalPage(Integer page, Integer limit, HospitalVo hospitalVo) {
        Map<String,Object> map=new HashMap<>();
        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //对象转换
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalVo,hospital);
        //创建查询实例
        Example<Hospital> example= Example.of(hospital,matcher);
        Criteria criteria=Criteria.byExample(example);
        if(hospitalVo.getHospitalTypes()!=null&&hospitalVo.getHospitalTypes().size()>0){
            criteria.orOperator(criteria.and("hospitalType").in(hospitalVo.getHospitalTypes()));
            //Criteria.and("hospitalType").in(hospitalVo.getHospitalTypes());
        }
        List<Hospital> mappedResults = mongoTemplate.aggregate(Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.skip(page - 1), Aggregation.limit(limit)), Hospital.class, Hospital.class).getMappedResults();
        final CountVo countVo = mongoTemplate.aggregate(Aggregation.newAggregation(Aggregation.match(criteria), Aggregation.count().as("count")), Hospital.class, CountVo.class).getUniqueMappedResult();
        mappedResults.stream().forEach(s->{
            s.setHospitalType(dictFeignClient.getNameByCN("HOSPTYPE",s.getHospitalType()));
        });
        map.put("content",mappedResults);
        map.put("totalElements",countVo==null?0:countVo.getCount());
        return map;
    }

    @Override
    public ArrayList<ProAndCityVo> getProAndCity(String dictoryCode, String value) {
        ArrayList<ProAndCityVo> proAndCityByCN = dictFeignClient.getProAndCityByCN(dictoryCode, value);
        return proAndCityByCN;
    }

    @Override
    public Map<String, Object> getHospitalRule(HospitalVo hospitalVo) {
        Map<String,Object> map=new HashMap<>();
        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        //对象转换
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalVo,hospital);
        //创建查询实例
        Example<Hospital> example= Example.of(hospital,matcher);
        Criteria criteria=Criteria.byExample(example);
        Hospital mappedResults = mongoTemplate.aggregate(Aggregation.newAggregation(Aggregation.match(criteria)), Hospital.class, Hospital.class).getUniqueMappedResult();
        //医院类型转换
        mappedResults.setHospitalType(dictFeignClient.getNameByCN("HOSPTYPE",mappedResults.getHospitalType()));
        map.put("hospital",mappedResults);
        map.put("bookingRule",mappedResults.getBookingRule());
        return map;
    }

    @Override
    public Hospital getHospitalByHospitalCode(String hospitalCode) {
        return hospitalRepository.getHospitalByHospitalCode(hospitalCode);
    }
}
